﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using THS.HtmlHelpers;
using Veteran_cms.Models;

namespace Veteran_cms.Controllers
{
    public class ManageCommentController : BaseController
    {
        readonly Veterandb _ctx = new Veterandb();
        //
        // GET: /ManageAbout/
        const int PageSize = 6;
        public ActionResult IndexComments(int page = 1)
        {
            var model = new HomeAdminListViewModel();

            var comments = _ctx.comments.OrderByDescending(p => p.comment_id).ToList();
            model.Comments = comments.Skip((page - 1) * PageSize).Take(PageSize).ToList();
            model.CommentPageInfo = new PagingInfo { CurrentPage = page, ItemsPerPage = PageSize, TotalItems = comments.Count() };
            InitCommentStatus(new CommentStatu());
            return View(model);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="page"></param>
        /// <returns></returns>
        public ActionResult Paging(int page = 1)
        {
            var model = new HomeAdminListViewModel();
            var comments = _ctx.comments.OrderByDescending(p => p.comment_id).ToList();
            model.Comments = comments.Skip((page - 1) * PageSize).Take(PageSize).ToList();
            model.NewsArticlePageInfo = new PagingInfo { CurrentPage = page, ItemsPerPage = PageSize, TotalItems = comments.Count() };
            return PartialView("UCCommentList", model);
        }

        public ActionResult Details(int id)
        {
            // TODO: Add update logic here
            // if (!IsAuthenticateAdmin())
            //   return RedirectToAction("LogOn", "AdminHome");
            var cmt = _ctx.comments.SingleOrDefault(c => c.comment_id == id);
            if (cmt != null)
            {
                InitCommentStatus(cmt.is_active);
                InitCommentTypes(cmt.comment_type);
                return View(cmt);
            }
            cmt = new comment();
            InitCommentStatus(new CommentStatu());
            InitCommentTypes(new CommentType());
            return View(cmt);
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Details(int id, HttpPostedFileBase uploadFile)
        {
            try
            {
                // TODO: Add update logic here
                // if (!IsAuthenticateAdmin())
                //   return RedirectToAction("LogOn", "AdminHome");
                var comment = _ctx.comments.SingleOrDefault(p => p.comment_id == id);

                UpdateModel(comment);
                _ctx.SaveChanges();
                if (comment != null)
                {
                    InitCommentStatus(comment.is_active);
                    InitCommentTypes(comment.comment_type);
                }
                ViewData["Msg"] = "Đã cập nhật!";
                return View(comment);
            }
            catch
            {
                ViewData["Msg"] = "Đã có lỗi xẩy ra. Vui lòng kiểm tra lại dữ liệu!";
                return View();
            }
        }

        public ActionResult Delete(int id)
        {
            // TODO: Add delete logic here
            //if (!IsAuthenticateAdmin())
            //    return RedirectToAction("LogOn", "AdminHome");
            if (id <= 0)
                return RedirectToAction("Delete", "ManageComment", new comment());
            var comment = _ctx.comments.SingleOrDefault(p => p.comment_id == id);
            _ctx.DeleteObject(comment);
            _ctx.SaveChanges();
            return RedirectToAction("IndexComments");
        }

        public ActionResult Create(int objectId, string commentType)
        {
            var cmt = new comment { comment_type = commentType, object_id = objectId };
            InitCommentStatus(cmt.is_active);
            InitCommentTypes(cmt.comment_type);
            return View(cmt);
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Create([Bind(Exclude = "comment_id")]comment comment)
        {
            // TODO: Add update logic here
            // if (!IsAuthenticateAdmin())
            //   return RedirectToAction("LogOn", "AdminHome");
            //con thieu nen ko cap nhat duoc .
            //1. email khong cho phep null
            //2. Ip khong cho phép null
            //3. is_active khong cho phep null
            //hiện tai em thieu nhung van de do nen ko save duoc.
            //trong function create tren page em khong can dung new{id=Mode.comment_id} dau
            // em con thieu commentParent_id nua
            try
            {
                comment.created_date = DateTime.Now;
                comment.ip = GetUserIp();

                _ctx.AddTocomments(comment);
                _ctx.SaveChanges();
                ViewData["Msg"] = "Đã tạo thành công!";
                return RedirectToAction("IndexComments");
            }
            catch
            {
                ViewData["Msg"] = "Đã có lỗi xẩy ra. Vui lòng kiểm tra lại dữ liệu!";
                return View(string.Empty);
            }
        }

        #region --Utitlies-
        private void InitCommentTypes(object selected)
        {
            var commentTypes = new List<CommentType>
                {
                    new CommentType { No = CommentTypes.News.ToString(), Name = "Tin tức" }, 
                    new CommentType { No = CommentTypes.Blog.ToString(), Name = "Blog" },
                    new CommentType { No = CommentTypes.Comment.ToString(), Name = "Comment" }
                };
            ViewData["CommentTypes"] = new SelectList(commentTypes.AsEnumerable(), "No", "Name", selected);
        }
        private void InitCommentStatus(object selected)
        {
            var commentTypes = new List<CommentStatu>
                {
                    new CommentStatu { No = (int)CommentStatus.Waiting, Name = "Chờ duyệt" }, 
                    new CommentStatu { No = (int)CommentStatus.Accept, Name = "Cho phép" }, 
                    new CommentStatu { No = (int)CommentStatus.NoAccept, Name = "Không cho phép" }
                };
            ViewData["CommentStatus"] = new SelectList(commentTypes.AsEnumerable(), "No", "Name", selected);
        }
        public string GetUserIp()
        {
            var ipList = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            return !string.IsNullOrEmpty(ipList) ? ipList.Split(',')[0] : Request.ServerVariables["REMOTE_ADDR"];
        }

        #endregion
    }
}
